package com.reggie.background.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reggie.background.dto.DishDto;
import com.reggie.background.entity.Dish;
import com.reggie.background.entity.DishFlavor;
import com.reggie.background.service.DishFlavorService;
import com.reggie.background.service.DishService;
import com.reggie.background.mapper.DishMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author 1
* @description 针对表【dish(菜品管理)】的数据库操作Service实现
* @createDate 2022-07-15 14:14:23
*/
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish>
    implements DishService{
@Autowired
private DishFlavorService dishFlavorService;

    /**
     * 保存菜品同时保存菜品的口味
     * @param dishdto
     * @return
     */
    @Transactional
    @Override
    public boolean saveDishDao(DishDto dishdto) {
        //保存菜品
        boolean save = this.save(dishdto);

        //先处理口味和菜品的多对一关系（将菜品id设置到口味集合里）
        List<DishFlavor> flavors = dishdto.getFlavors();
        List<DishFlavor> collect = flavors.stream().map(item -> {
            item.setDishId(dishdto.getId());
            return item;
        }).collect(Collectors.toList());
        //保存处理后的口味集合
        boolean result = dishFlavorService.saveBatch(collect);
        return result&&save;
    }
    @Transactional
    @Override
    public boolean updateDishDao(DishDto dishdto) {
        //先更新菜品信息
        boolean  result1 = this.updateById(dishdto);

        //根据需要更新的菜品id删除掉原来的口味数据（采用《先删除旧口味再插入新的口味》来代替更新口味的操作）
        List<DishFlavor> flavors = dishdto.getFlavors();
        LambdaQueryWrapper<DishFlavor> rq=new LambdaQueryWrapper<>();
        rq.eq(DishFlavor::getDishId, dishdto.getId());
        boolean remove1 = dishFlavorService.remove(rq);
        //处理前端想更新的口味集合，然后写入数据库
        List<DishFlavor> collect = flavors.stream().map(item -> {
            item.setDishId(dishdto.getId());
            return item;
        }).collect(Collectors.toList());
        boolean result2 = dishFlavorService.saveBatch(collect);
        return result1&&result2;
    }
}




